import React, { FC } from "react";
import { Typography, Button, Space, Form, Input, message } from "antd";
import { UserAddOutlined } from "@ant-design/icons";
import styles from "./register.module.scss";
import { LOGIN_PATH } from "../../router";
import { Link, useNavigate } from "react-router-dom";
import { registerSer } from "../../services/user";
import { useRequest } from "ahooks";

type FieldType = {
  username: string;
  password: string;
  confirm: string;
  nickname: string;
};

const { Title } = Typography;
const Register: FC = () => {
  const nav = useNavigate();

  async function registerfn(values: FieldType) {
    const { username, password, nickname } = values;
    await registerSer(username, password, nickname);
  }
  const { run: handleRegiseter } = useRequest(registerfn, {
    manual: true,
    onSuccess: () => {
      message.success("注册成功");
      nav(LOGIN_PATH);
    },
  });

  const onFinish = (values: FieldType) => {
    handleRegiseter(values);
  };

  return (
    <div className={styles.container}>
      <Space>
        <Title level={2}>
          <UserAddOutlined />
        </Title>
        <Title level={3}>用户注册</Title>
      </Space>
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
      >
        <Form.Item label="账号" name="username">
          <Input />
        </Form.Item>
        <Form.Item label="密码" name="password">
          <Input.Password />
        </Form.Item>
        <Form.Item label="确认密码" name="confirm">
          <Input.Password />
        </Form.Item>
        <Form.Item label="用户名" name="nickname">
          <Input />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
          <Space>
            <Button type="primary" htmlType="submit">
              注册
            </Button>
            <Link to={LOGIN_PATH}>已有用户，现去登录</Link>
          </Space>
        </Form.Item>
      </Form>
    </div>
  );
};
export default Register;
